package com.starblink.search.result.ui.fragment.user

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.rocketreserver.SearchAccountsQuery
import com.starblink.rocketreserver.fragment.AccountF
import kotlinx.coroutines.launch

internal class UserResultVM: BaseViewModel() {

    var keyworkd = ""

    var pageNo = 1

    val contentList = arrayListOf<AccountF>()

    val contentLiveData = MutableLiveData<Boolean>()

    fun fetchUsers() {
        viewModelScope.launch {
            val notEmpty = SkGqlClient.skQuery(SearchAccountsQuery(
                content = keyworkd.optional(),
                pageNo = pageNo,
                pageSize = SIZE.optional(),
            ))?.let { res ->
                val list = res.data?.searchAccounts?.map { it.accountF }

                if (list?.isNotEmpty() == true) {
                    contentList.addAll(list)
                }

                list?.isNotEmpty() == true
            }

            if (pageNo == 1 && notEmpty != true) {
                loadNoData()
            } else {
                loadSuccess()
            }
            contentLiveData.postValue(notEmpty == true)
        }
    }

    companion object {

        private const val SIZE = 20

    }


}